import mongoose from 'mongoose';
import { config } from '@/config';
import { logger } from '@/utils/logger';

/**
 * MongoDB 连接选项
 */
const mongoOptions = {
  maxPoolSize: 10,
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
  bufferCommands: false
};

/**
 * 连接到 MongoDB
 */
export const connectMongoDB = async (): Promise<void> => {
  try {
    const uri = config.app.env === 'test' 
      ? config.database.mongodb.testUri 
      : config.database.mongodb.uri;
      
    await mongoose.connect(uri, mongoOptions);
    
    logger.info(`MongoDB 连接成功: ${uri}`);
  } catch (error) {
    logger.error('MongoDB 连接失败:', error);
    process.exit(1);
  }
};

/**
 * 断开 MongoDB 连接
 */
export const disconnectMongoDB = async (): Promise<void> => {
  try {
    await mongoose.disconnect();
    logger.info('MongoDB 连接已断开');
  } catch (error) {
    logger.error('断开 MongoDB 连接失败:', error);
  }
};

/**
 * 清空 MongoDB 数据库（仅用于测试环境）
 */
export const clearDatabase = async (): Promise<void> => {
  if (config.app.env !== 'test') {
    throw new Error('清空数据库操作仅允许在测试环境中执行');
  }
  
  try {
    const collections = await mongoose.connection.db?.collections();
    if (collections) {
      for (const collection of collections) {
        await collection.deleteMany({});
      }
    }
    logger.info('测试数据库已清空');
  } catch (error) {
    logger.error('清空测试数据库失败:', error);
    throw error;
  }
};

/**
 * MongoDB 连接事件监听
 */
mongoose.connection.on('connected', () => {
  logger.info('MongoDB 连接已建立');
});

mongoose.connection.on('error', (error) => {
  logger.error('MongoDB 连接错误:', error);
});

mongoose.connection.on('disconnected', () => {
  logger.info('MongoDB 连接已断开');
});

// 优雅关闭连接
process.on('SIGINT', async () => {
  await disconnectMongoDB();
  process.exit(0);
});

export default mongoose;